<template>
  <wd-form-item
    v-if="
      typeof props.component.display == 'undefined' ||
      props.component.display === true
    "
    :component="props.component"
    :custom-field="props.customField"
  >
    <slot :name="`form-${props.component.dataIndex}`" v-bind="props.component">
      <el-select
        v-model="value"
        :placeholder="
          props.component.placeholder ?? `请选择${props.component.title}`
        "
        :size="props.component.size"
        :disabled="props.component.disabled"
        :clearable="props.component.allowClear ?? true"
        :filterable="props.component.filterable ?? true"
        :multiple="
          props.component.multiple ||
          ['transfer', 'checkbox'].includes(props.component.formType)
        "
      >
        <el-option
          v-for="(item, index) in dictList[dictIndex] ?? []"
          :key="index"
          :label="item.label"
          :value="item.value"
          :disabled="item.disabled"
        />
      </el-select>
    </slot>
  </wd-form-item>
</template>

<script setup>
import { ref, inject, watch } from "vue";
import { get, set, isUndefined } from "lodash";

const props = defineProps({
  component: { type: Object, required: true },
  customField: { type: String, default: undefined },
});

const formModel = inject("formModel");
const dictList = inject("dictList");

const index = props.customField ?? props.component.dataIndex;
const dictIndex = index.match(/^(\w+\.)\d+\./)
  ? index.match(/^(\w+\.)\d+\./)[1] + props.component.dataIndex
  : props.component.dataIndex;
const value = ref(
  get(formModel.value, index, props.component.multiple ? [] : "")
);

watch(
  () => get(formModel.value, index),
  (vl) => (value.value = vl)
);

watch( () => value.value, v => {
  set(formModel.value, index, v)
  index.indexOf('.') > -1 && delete formModel.value[index]
} )

if (isUndefined(value.value) && props.component.multiple) {
  value.value = [];
} else if (
  !isUndefined(value.value) &&
  props.component.dict &&
  (props.component.dict.name || props.component.dict.data)
) {
  value.value = String(value.value);
}
</script>